package com.zl.basic.model;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * User: zl email:c3tc3tc3t@126.com Date: 14-2-24 Time: 下午3:27
 */
public class Captcha {
  private int width;
  private int height;
  private int num;
  private String code;
  private static Captcha captcha = new Captcha();
  private static final Random ran = new Random();

  private Captcha() {
    code = "123465789abcdefghijklmnopqrstuvwxyz";
    num = 4;
  }

  public static Captcha getInstance() {
    return captcha;
  }

  public void set(int width, int height, int num, String code) {
    this.width = width;
    this.height = height;
    this.setNum(num);
    this.setCode(code);
  }

  public void set(int width, int height) {
    this.width = width;
    this.height = height;

  }

  public int getWidth() {
    return width;
  }

  public void setWidth(int width) {
    this.width = width;
  }

  public int getHeight() {
    return height;
  }

  public void setHeight(int height) {
    this.height = height;
  }

  public int getNum() {
    return num;
  }

  public void setNum(int num) {
    this.num = num;
  }

  public String getCode() {
    return code;
  }

  public void setCode(String code) {
    this.code = code;
  }

  public String generateCode() {
    StringBuilder buffer = new StringBuilder();
    for (int i = 0; i < num; i++) {
      buffer.append(code.charAt(ran.nextInt(code.length())));
    }
    return buffer.toString();
  }

  public BufferedImage getnerateCheckImg(String checkcode) {
    // 创建图片对象
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    // 获取图片画笔
    Graphics2D graphics = img.createGraphics();
    // 画背景
    graphics.setColor(Color.WHITE);
    graphics.fillRect(0, 0, width, height);
    // 画边框
    graphics.setColor(Color.BLACK);
    graphics.drawRect(0, 0, width - 1, height - 1);
    // 字体设置
    Font font = new Font("宋体", Font.BOLD + Font.ITALIC, (int) (height * 0.8));
    graphics.setFont(font);
    for (int i = 0; i < num; i++) {
      graphics.setColor(new Color(ran.nextInt(255), ran.nextInt(255), ran.nextInt(255)));
      graphics.drawString(String.valueOf(checkcode.charAt(i)), i * (width / num) + 4,
          (int) (height * 0.8));
    }
   /* // 加点
    for (int i = 0; i < (width + height); i++) {

      graphics.setColor(new Color(ran.nextInt(255), ran.nextInt(255), ran.nextInt(255)));
      graphics.drawOval(ran.nextInt(width), ran.nextInt(height), 1, 1);
    }
    // 加一些线
    for (int i = 0; i < 4; i++) {
      graphics.setColor(new Color(ran.nextInt(255), ran.nextInt(255), ran.nextInt(255)));
      graphics.drawLine(0, ran.nextInt(height), width, ran.nextInt(height));
    }*/

    return img;
  }

}
